#pragma once
#include <memory>
#include <functional>
#include <sys/wait.h>
#include "Common.hpp"
#include "Socket.hpp"
#include "Log.hpp"

using namespace mySocket;
using namespace myLog;
using ioservice_t = std::function<void(std::shared_ptr<Socket>, const InetAddr&)>;


class TcpServer{
public:
    TcpServer(uint16_t port)
        :_port(port),
        _is_running(false),
        _server_socket(std::make_unique<TcpSocket>())
    {}

    ~TcpServer(){}

    void Init(){
        _server_socket->CreateServerTcpSocket(_port);
    }

    void Run(ioservice_t io_service){
        _is_running = true;
        while(_is_running){
            InetAddr client;
            int fd = _server_socket->AcceptOrDie(&client);
            std::shared_ptr<Socket> server_io_socket = std::make_shared<TcpSocket>(fd);
            
            //多进程来执行服务！
            pid_t id = fork();
            if(id < 0){
                LOG(LogLevel::FATAL) << "fork error";
                exit(FORK_ERROR);
            }
            else if(id == 0){
                //子进程
                if(fork() > 0) exit(OK); 

                //孙子进程 -> 孤儿进程，系统自动回收
                io_service(server_io_socket, client);
                //实现一次短服务！
                server_io_socket->Close();
                exit(OK);
            }
            else{
                //父进程
                int rid = waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
    }
private:
    uint16_t _port;
    bool _is_running;
    std::unique_ptr<Socket> _server_socket;
};